﻿using Exiled.API.Features;
using RgCore.Database;
using RgCore.GameData;
using RgCore.Modules;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;

namespace AdminOnlineTimer
{
    public class AdminConfig : IConfig
    {
        [Description("表名，用于记录管理在线时长")]
        public string TableName { get; set; } = "cdcp_admin_online";
    }

    public class TimerPlugin : RgPlugin
    {
        public override string Name => "管理在线计时";

        public override string Id => "admin_online_timer";

        public override object Config { get; set; } = new AdminConfig();

        public Thread thread;
        public string TableName => (Config as AdminConfig).TableName;
        public Dictionary<string, int> Minutes = new Dictionary<string, int>();

        public override void OnDisabled()
        {
            if (DatabaseController.DatabaseDisabled)
            {
                return;
            }
            GameplayData.OnInitializingData -= GameplayData_OnInitializingData;
            thread.Abort();
            thread = null;
        }

        public override void OnEnabled()
        {
            if (DatabaseController.DatabaseDisabled)
            {
                Log.Warn("由于数据库未启用，此插件不加载");
                return;
            }
            GameplayData.OnInitializingData += GameplayData_OnInitializingData;
            Thread t = new Thread(TimerUpdate) { Name = "管理在线计时" };
            thread = t;
            t.Start();
            foreach (Player admin in Player.List.Where(x => x.Group != null))
            {
                GameplayData_OnInitializingData(admin);
            }
        }

        private void TimerUpdate()
        {
            while (true)
            {
                try
                {
                    foreach (Player admin in Player.List.Where(x => x.Group != null && Minutes.ContainsKey(x.UserId)))
                    {
                        Minutes[admin.UserId]++;
                        var filter = new Dictionary<string, object>() { { "userid", admin.UserId } };
                        NoResponseCommandRequest cmd = new NoResponseCommandRequest(TableName, RequestType.Update,
    new Dictionary<string, object>() { { "minutes", Minutes[admin.UserId] } }, filter);
                        _ = cmd.ProcessNonQuery();
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                Thread.Sleep(60000);
            }
        }

        private async void GameplayData_OnInitializingData(Player player)
        {
            if (DatabaseController.DatabaseDisabled)
                return;
            if (player.Group != null)
            {
                try
                {
                    var filter = new Dictionary<string, object>() { { "userid", player.UserId } };
                    var filter2 = new Dictionary<string, object>() { { "userid", player.UserId }, { "nickname", player.Nickname } };
                    QueryCommandRequest cmd = new QueryCommandRequest(TableName, filter, true, "minutes") { Insert_Keys = filter2 };
                    int minute = int.Parse((await cmd.GetResponseResult()).First()["minutes"].ToString());
                    if (!Minutes.ContainsKey(player.UserId))
                        Minutes.Add(player.UserId, 0);
                    Minutes[player.UserId] = minute;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
        }
    }
}